<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="任务代码" prop="taskCode">
        <el-checkbox-group v-model="formData.taskCode" placeholder="请选择任务代码" multiple>
          <el-checkbox
            v-for="dict in getStrDictOptions(DICT_TYPE.DOUYIN_FLOW_TASK_CODE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-checkbox-group>
      </el-form-item>
      <div v-if="formData.taskCode.includes('rzspss')">
        <el-form-item label="搜素关键字" prop="comment">
          <el-input v-model="formData.context.keyword" placeholder="搜素关键字" />
        </el-form-item>

        <elRow>
          <elCol :span="12">
            <elFormItem prop="pxyj" label="排序依据">
              <elRadioGroup v-model="formData.context.pxyj">
                <elRadio label="综合排序" value="综合排序">综合排序</elRadio>
                <elRadio label="最新发布" value="最新发布">最新发布</elRadio>
                <elRadio label="最多点赞" value="最多点赞">最多点赞</elRadio>
              </elRadioGroup>
            </elFormItem>
          </elCol>
          <elCol :span="12">
            <elFormItem prop="fbsj" label="发布时间">
              <elRadioGroup v-model="formData.context.fbsj">
                <elRadio label="不限" value="不限">不限</elRadio>
                <elRadio label="一天内" value="一天内">一天内</elRadio>
                <elRadio label="一周内" value="一周内">一周内</elRadio>
                <elRadio label="半年内" value="半年内">半年内</elRadio>
              </elRadioGroup>
            </elFormItem>
          </elCol>
          <elCol :span="12">
            <elFormItem prop="spsc" label="视频时长">
              <elRadioGroup v-model="formData.context.spsc">
                <elRadio label="不限" value="不限">不限</elRadio>
                <elRadio label="1分钟以下" value="1分钟以下">1分钟以下</elRadio>
                <elRadio label="1-5分钟" value="1-5分钟">1-5分钟</elRadio>
                <elRadio label="5分钟以上" value="5分钟以上">5分钟以上</elRadio>
              </elRadioGroup>
            </elFormItem>
          </elCol>
          <elCol :span="12">
            <elFormItem prop="ssfw" label="搜索范围">
              <elRadioGroup v-model="formData.context.ssfw">
                <elRadio label="不限" value="不限">不限</elRadio>
                <elRadio label="关注的人" value="关注的人">关注的人</elRadio>
                <elRadio label="最近看过" value="最近看过">最近看过</elRadio>
                <elRadio label="还未看过" value="还未看过">还未看过</elRadio>
              </elRadioGroup>
            </elFormItem>
          </elCol>
          <elCol :span="12">
            <elFormItem prop="nrxs" label="内容形式">
              <elRadioGroup v-model="formData.context.nrxs">
                <elRadio label="不限" value="不限">不限</elRadio>
                <elRadio label="视频" value="视频">视频</elRadio>
                <elRadio label="图文" value="图文">图文</elRadio>
              </elRadioGroup>
            </elFormItem>
          </elCol>
        </elRow>
      </div>
      <el-form-item label="优先级" prop="priority">
        <el-input type="number" v-model="formData.priority" placeholder="请输入优先级" />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择任务状态">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DOUYIN_FLOW_TASK_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注信息" prop="comment">
        <el-input v-model="formData.comment" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { FlowTaskApi, FlowTaskVO } from '@/api/douyin/task'
import { ref } from 'vue'

/** 任务信息 表单 */
defineOptions({ name: 'FlowTaskForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  taskCode: [] as string[],
  context: {
    keyword: undefined,
    pxyj: '综合排序',
    fbsj: '不限',
    spsc: '不限',
    ssfw: '不限',
    nrxs: '不限'
  },
  priority: undefined,
  status: undefined,
  comment: undefined
})
const formRules = reactive({
  taskCode: [{ required: true, message: '任务代码不能为空', trigger: 'change' }],
  status: [{ required: true, message: '任务状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await FlowTaskApi.getFlowTask(id)
      formData.value = {
        ...data,
        context: JSON.parse(data.context),
        taskCode: JSON.parse(data.taskCode)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    let data = {
      ...formData.value,
      context: JSON.stringify(formData.value.context),
      taskCode: JSON.stringify(formData.value.taskCode)
    }
    const req = data as unknown as FlowTaskVO
    if (formType.value === 'create') {
      await FlowTaskApi.createFlowTask(req)
      message.success(t('common.createSuccess'))
    } else {
      await FlowTaskApi.updateFlowTask(req)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    taskCode: [],
    context: {
      keyword: undefined,
      pxyj: '综合排序',
      fbsj: '不限',
      spsc: '不限',
      ssfw: '不限',
      nrxs: '不限'
    },
    priority: undefined,
    status: undefined,
    comment: undefined
  }
  formRef.value?.resetFields()
}
</script>
